<?php

namespace Xtsb\Cims\Push;

use Xtsb\Cims\Exception\ApiErrorDesc;
use Xtsb\Cims\Exception\ApiException;
use getui\GTClient;
use getui\request\push\android\GTAndroid;
use getui\request\push\android\GTThirdNotification;
use getui\request\push\android\GTUps;
use getui\request\push\GTNotification;
use getui\request\push\GTPushChannel;
use getui\request\push\GTPushMessage;
use getui\request\push\GTPushRequest;
use getui\request\push\GTRevoke;
use getui\request\push\GTSettings;
use getui\request\push\GTStrategy;
use getui\request\push\ios\GTAlert;
use getui\request\push\ios\GTAps;
use getui\request\push\ios\GTIos;
use getui\request\push\ios\GTMultimedia;
use think\facade\Db;

class GPush
{
  // 访问的域名
  private $domainUrl = 'https://restapi.getui.com';
  // 环境配置
  private $env = [
    'android' => [
      'app_key' => '6W4dxLYqHaAri9uW6KPWc6',
      'app_id' => 'wEZ2H2i0Jn5Rr3mnSNwbs8',
      'master_secret' => 'zD383N2Fvo7XpdP99e645A',
      'app_secret' => 'kQrzO15aqv8lCzi9iZ1brA',
      'pkg' => 'io.dcloud.taihaoguan',  // 包名
    ],
    'ios' => [],
  ];
  private $api = null;
  private $token = null;
  private $taskId = null;

  public function __construct()
  {
    $this->api = new GTClient(
      $this->domainUrl,
      $this->env['android']['app_key'],
      $this->env['android']['app_id'],
      $this->env['android']['master_secret']
    );
  }

  /**
   * 指定app用户推送消息
   * @param $data
   * @return array|mixed
   */
  public function pushToSingleByCid($data, $type='user')
  {
    $content = json_encode($data);
    // 根据业务$uid 查询 client_id 推送
    if($type == 'worker'){
      $worker_id = $data['worker_id'];  // 业务UID

      $cidArr = Db::name('user_client')
        ->alias('uc')
        ->leftJoin('worker s', 's.id = uc.uid')
        ->where(['sa.id' => $worker_id])->whereNull('cuid')
        ->column('uc.client_id');
    }else{
      $uid = $data['uid'];  // 业务UID

      $cidArr = Db::name('user_client')
        ->alias('uc')
        ->leftJoin('staff s', 's.uid = uc.uid')
        ->leftJoin('staff_access sa', 'sa.staff_id = s.id')
        ->where(['sa.id' => $uid])
        ->column('uc.client_id');
    }

    if (count($cidArr) == 1) {
      $push = $this->getParam($content);
      $push->setCid($cidArr[0]);
      $result = $this->api
        ->pushApi()
        ->pushToSingleByCid($push);
      if ($result['code']) {
        $result = ['code' => $result['code'], 'msg' => '推送失败：' . $result['msg']];
      }
    } else {
      $result = ['code' => 100, 'msg' => '未登录App，推送失败'];
    }
    return $result;
  }

  private function getParam($content)
  {
    $push = new GTPushRequest();
    $push->setRequestId($this->micro_time());
    //设置setting
    $set = new GTSettings();
    $set->setTtl(3600000);
    $strategy = new GTStrategy();
    $strategy->setDefault(GTStrategy::STRATEGY_GT_FIRST);
    $set->setStrategy($strategy);
    $push->setSettings($set);
    //设置PushMessage，
    $message = new GTPushMessage();
    $message->setTransmission($content);
    $push->setPushMessage($message);

    return $push;
  }

  private function micro_time()
  {
    list($usec, $sec) = explode(" ", microtime());
    $time = ($sec . substr($usec, 2, 3));
    return $time;
  }

  /**
   * 查看任务
   * @param $taskId
   * @return mixed
   */
  public function queryPushResultByTaskIds($taskId)
  {
    return $this->api->statisticsApi()->queryPushResultByTaskIds($taskId);
  }

  public function pushAll($content)
  {
    $push = $this->getParam($content);
    return $this->api->pushApi()->pushAll($push);
  }

}